<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Crons extends CI_Controller {

	public $data = array();

	function __construct()
	{
		parent::__construct();

		$this->load->model('merchant_model');
		$this->load->model('reports_model');
		
		$this->load->config('regions');
		$this->load->library('form_validation');
		$this->load->library('curl');
		$this->load->helper('form');
		$this->load->helper('download');
	}
		
	function update_reports_status( $request_id = null, $from_date = null, $to_date = null  )
	{
		$where = array();
		
		if( !is_null($request_id) )
			$where['report_request_id'] = $request_id;
		
		if( !is_null($from_date) && !is_null($to_date) )
		{
			$where['from_date'] = $from_date;
			$where['to_date'] = $to_date;
		}

		$where_notin = array('_DONE_NO_DATA_','_CANCELLED_','_DONE_'); 

		$records = $this->reports_model->get_report_requests($where,$where_notin);
		
		$ids = array();
		foreach($records as $row)
		{
			$ids[$row['merchant_id']][] = $row['report_request_id'];
		}
		
		foreach( $ids as $merchant_id => $id )
		{
			$report_list_url = site_url('api/reports/reportRequestList/format/json?KEY='.$merchant_id);
			$report_list_url .= '&ReportRequestIdList='.implode('|', $id);
			
			$result = $this->get_api_data( $report_list_url );
			$result = json_decode($result, TRUE);
			
			$tmp = array();
			if( isset($result['GetReportRequestListResult']) )
			{
				$result = current($result['GetReportRequestListResult']);
				if( isset($result['ReportRequestInfo']) && is_array($result['ReportRequestInfo']) )
				$tmp		= $result['ReportRequestInfo'];
			}
			
			$request_infos = array();
			if( count($id) == 1 )
				$request_infos[] =  $tmp;
			else 
				$request_infos = $tmp;
			
			//print_r($request_infos);die;
			foreach($request_infos as $row)
			{
				$report_id = isset($row['GeneratedReportId'])?$row['GeneratedReportId']:'';
				$report_generated_date = isset($row['CompletedDate'])?get_DB_Date($row['CompletedDate']):'';

				$this->db->where('report_request_id', $row['ReportRequestId']);
				$this->db->update('reports', array('report_status' => $row['ReportProcessingStatus'], 'report_id' => $report_id,'report_generated_date'=>$report_generated_date));	
			}
		}
		
		
		//Get setllement reports for all merchants
		
		$merchants = $this->merchant_model->get_merchant_id_list();
		
		foreach($merchants as $merchant_id)
		{
			//get settlement reports
			$report_type = '_GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE_';
			$report_list_url = site_url('api/reports/reportRequestList/format/json?KEY='.$merchant_id);
			$report_list_url .= '&ReportTypeList='.$report_type;
			$report_list_url .= '&ReportProcessingStatusList=_DONE_|_DONE_NO_DATA_';
				
			$result = $this->get_api_data( $report_list_url );
			$result = json_decode($result, TRUE);
				
			$tmp = array();
			if( isset($result['GetReportRequestListResult']) )
			{
				$result = current($result['GetReportRequestListResult']);
				if( isset($result['ReportRequestInfo']) && is_array($result['ReportRequestInfo']) )
				$tmp		= $result['ReportRequestInfo'];
			}
			
			$request_infos = array();
			if( !count($tmp) )
				$request_infos = $tmp;
			else if( !isset($tmp[0]) )
				$request_infos[] =  $tmp;
			else
				$request_infos = $tmp;
			
			foreach($request_infos as $row)
			{
				if( !$this->reports_model->is_exists(array('report_request_id' => $row['ReportRequestId'])) )
				{
					$report_id = isset($row['GeneratedReportId'])?$row['GeneratedReportId']:'';
					$report_generated_date = isset($row['CompletedDate'])?get_DB_Date($row['CompletedDate']):null;
					
					$insert = array();
					$insert['merchant_id'] 				= $merchant_id;
					$insert['report_type'] 				= $report_type;
					$insert['from_date'] 				= get_DB_Date($row['StartDate']);
					$insert['to_date'] 					= get_DB_Date($row['EndDate']);
					$insert['date_interval'] 			= ceil((strtotime($insert['to_date'])-strtotime($insert['from_date']))/(60*60*24));
					$insert['report_request_id']		= $row['ReportRequestId'];
					$insert['report_id'] 				= $report_id;
					$insert['report_status'] 			= $row['ReportProcessingStatus'];
					$insert['report_generated_date'] 	= $report_generated_date;
						
					$this->db->insert('reports', $insert);
						
				}
			
			}
			//echo '<pre>';print_r($request_infos);die;
		}
		
	
	}
	
	
	function fetch_report( $report_type = null )
	{
		$where = array();
		
		if( !is_null($report_type) )
			$where['report_type'] = $report_type;
		
		$where['report_status'] = '_DONE_';
		$where['is_fetched'] = 'no';
		
		$records = $this->reports_model->get_report_requests($where);
		//echo '<pre>';print_r($records);die;
		foreach($records as $record)
		{
			$report_url = site_url("api/reports/report/format/json?ReportId={$record['report_id']}&KEY={$record['merchant_id']}");
			//die($report_url);
			$result = $this->get_api_data( $report_url );
			
			$result = json_decode($result, TRUE);
			//echo '<pre>';print_r($result);die;
			$insert = array();

			if($result['filePath'] == '')
				continue;

			$content = file_get_contents($result['filePath']);

			if($content == '')
				continue;

			$insert['content'] 		= $content;
			$insert['file_path'] 	= $result['filePath'];
			$insert['is_fetched']   ='yes';
			$csv_str = $this->amazon_mws->convert_to_csv($result['filePath'], 'tab');
			$insert['content_csv'] = $csv_str;
			
			$this->db->where('report_id', $record['report_id']);
			$this->db->update('reports', $insert);
			//echo '<pre>';print_r($insert);die;

			//ActionLog
			$action_data = array();
			$action_data['merchant_id'] = $record['merchant_id'];
			$action_data['type']='reports';
			$action_data['action']= 'The '.$record['report_type'].' report fetched success from '.date('Y-m-d H:i',local_to_gmt(strtotime($record['from_date']))).' to '.date('Y-m-d H:i',local_to_gmt(strtotime($record['to_date']))).' and the status is DONE';				
			
			actionlog($action_data);
		}
	}	

	
	function schedule_report( $type = 'daily_once' )
	{
		$this->load->config('crons');
		
		$crons = $this->config->item('crons');
		
		$records = array();
		
		if( isset($crons[$type]) )
		{
			$records = $crons[$type];
		}
		
		//echo '<pre>';print_r($records);die;
		foreach( $records as $merchant_id => $rows )
		{
			foreach( $rows as $report_type => $val )
			{
				$this->schedule($merchant_id, $report_type, $val['interval']);
			}			
		}
		
	}
	
	function schedule( $merchant_id = null, $report_type = null, $interval_date = null  )
	{

		if(is_null($merchant_id) && is_null($report_type) && is_null($interval_date) )
			return false;

		$end_date = date('Y-m-d H:i:s');
		$start_date = date('Y-m-d H:i:s',strtotime('-'.$interval_date.' days',strtotime($end_date)));

		//get merchant details
		$merchant_details = $this->merchant_model->get_by_merchant_id($merchant_id);

		if(empty($merchant_details))
			return false;
		
		$report_request_url = site_url('api/reports/requestReport/format/json?KEY='.$merchant_details['merchant_id']);
		
		if( $report_type )
			$report_request_url .= '&ReportType='.urlencode($report_type);
		
		if( $start_date  && $end_date)
			$report_request_url .= '&StartDate='.urlencode($start_date).'&EndDate='.urlencode($end_date);
		
		//die($report_request_url);
		$result = $this->get_api_data( $report_request_url );
		$result = json_decode($result, TRUE);

		//echo '<pre>';print_r($result);die;
		$action_data = array();
		$action_data['merchant_id'] = $merchant_details['merchant_id'];
		$action_data['type']='reports';

		if( isset($result['RequestReportResult']) )
			{
				$result = current($result['RequestReportResult']);
				if( isset($result['ReportRequestInfo']) )
				$data['records']	= $result['ReportRequestInfo'];
				
				$start_date = date('Y-m-d H:i',local_to_gmt(strtotime($start_date)));
				$end_date = date('Y-m-d H:i',local_to_gmt(strtotime($end_date)));
				
				//insert in to request table
				$insert = array();
				$insert['merchant_id'] 	= $merchant_details['merchant_id'];
				$insert['report_type'] 	= $report_type;
				$insert['date_interval']= $interval_date;
				$insert['from_date'] 	= $start_date;
				$insert['to_date'] 		= $end_date;
				$insert['report_request_id']		= $data['records']['ReportRequestId'];
				$insert['report_status']		= $data['records']['ReportProcessingStatus'];
				$insert['created_time'] 	= date('Y-m-d H:i',local_to_gmt(time()));

				$this->db->insert('reports', $insert);
								
				$action_data['action']= 'The '.$report_type.' report requested success from '.$start_date.' to '.$end_date.' and the status is '.$data['records']['ReportProcessingStatus'];				
				
			}
			else 
			{
			    $action_data['action']= 'Failed to request the '.$report_type.' report from '.$start_date.' to '.$end_date;				

			}

			//ActionLog
			actionlog($action_data);

	}
	
	
	function remove_older_records( $age = 30 )
	{
		$records = $this->reports_model->get_older_reports($age);
		
		foreach($records as $record)
		{
			$fname = end(explode('/', $record['file_path']));
			@unlink('./assets/reports/'.$fname);
			
			$this->db->delete('reports', array('id' => $record['id']));
		}
		
	}
	
	
	function get_api_data( $url = '')
	{
		$this->curl->create($url);
        $this->curl->option('SSL_VERIFYPEER', false); // for ssl
        $this->curl->option('RETURNTRANSFER', true);
        $data = $this->curl->execute();
		
        return $data;
        
	}

	function test()
	{
		$fpath = 'http://amz.mws/assets/reports/reports-24370804533-20150309IST170006.txt';
		$csv_str = $this->amazon_mws->convert_to_csv($fpath, 'tab');
		echo $csv_str;
	}

	
}

/* End of file crons.php */
/* Location: ./application/controllers/crons.php */
